package com.ruoyi.pcwl.utils;


import com.fasterxml.jackson.databind.*;

import java.util.ArrayList;
import java.util.List;

public class JacksonUtil {

    private static ObjectMapper mapper = new ObjectMapper()
            //设置空值不需要转换
            //.setSerializationInclusion(JsonInclude.Include.NON_NULL)
            .enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
            .enable(MapperFeature.USE_ANNOTATIONS);

    public static String toJSONString(Object object) {
        return toJSONString(object, mapper);
    }

    public static String toJSONString(Object object, ObjectMapper objectMapper) {
        String res = null;
        try {
            res = objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            res = null;
        }
        return res;
    }

    public static <T> T toJavaObject(String json, Class<T> itemType) {
        return toJavaObject(json, mapper, itemType);
    }

    public static <T> T toJavaObject(String json, ObjectMapper objectMapper, Class<T> itemType) {
        T t = null;
        try {
            t = objectMapper.readValue(json, itemType);
        } catch (Exception e) {
            t = null;
        }
        return t;
    }

    public static <T> List<T> toJavaList(String json, Class<T> itemType) {
        return toJavaList(json, mapper, itemType);
    }

    public static <T> List<T> toJavaList(String json, ObjectMapper objectMapper, Class<T> itemType) {
        List<T> list = null;
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, itemType);
        try {
            list = objectMapper.readValue(json, javaType);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

}
